package 二叉树;

/**
 * 题目地址 https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xninbt/
 */
public class 将有序数组转化为二叉搜索树 {
    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
        this.left = left;
         this.right = right;
      }
  }
    public TreeNode sortedArrayToBST(int[] nums) {
         if (nums.length==0) return null;
         return sort(nums,0,nums.length-1);
    }

    private TreeNode sort(int[] nums, int start, int end) {
        if (start>end) return null;
        //找到中间节点
        int mid = (start+end)/2+(start+end)%2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = sort(nums,start,mid-1);
        root.right = sort(nums,mid+1,end);
        return root;
    }
}
